package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.service.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.ehcache.core.util.ByteBufferInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * @author: itheima
 * @create: 2022-05-19 11:23
 */
@Component
public class ArticleHtmlTask {


    @Autowired
    private IApArticleContentService articleContentService;

    @Autowired
    private IApArticleService articleService;


    /**
     * 注意使用：freemarker.template.Configuration对象
     */
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    /**
     * 创建传入参数对应文章ID 基于freemarker生成静态页html文件；将该文件上传到MinIO；更新文章表中静态页地址
     *
     * @param articleId
     */
    @Async("leadnewsExecutor")
    public void createAticleHtmlAndUpload(Long articleId) throws IOException, TemplateException {
        //1.封装模板需要参数-根据文章ID查询文章内容  TODO 模板中需要是内容字段 数组（集合）
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = articleContentService.getOne(queryWrapper);

        //2.基于Freemarker模板生成静态页
        Template template = configuration.getTemplate("article.ftl");

        //2.1 准备模板需要数据模型
        HashMap<String, Object> dataModel = new HashMap<>();
        dataModel.put("content", JSON.parseArray(apArticleContent.getContent()));

        //2.x 生成静态页文件
        StringWriter writer = new StringWriter();
        template.process(dataModel, writer);

        //3.将生成html文件上传到MinIO中
        byte[] bytes = writer.toString().getBytes();
        InputStream inputStream = new ByteArrayInputStream(bytes);
        String filePath = minIOService.upload(articleId + ".html", inputStream, "text/html");
        //4.更新文章表中静态化字段
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId, articleId);
        updateWrapper.set(ApArticle::getStaticUrl, filePath);
        updateWrapper.set(ApArticle::getSyncStatus, 1);
        articleService.update(updateWrapper);
    }

}
